今天就先替 Cart 加入 remove 的功能吧
// tests/CartTest.php
<?php
namespace Recca0120\Cart\Tests;
use Recca0120\Cart\Cart;
use Recca0120\Cart\Item;
use PHPUnit\Framework\TestCase;
class CartTest extends TestCase
{
/** @test */
public function 將商品加入購物車並驗證商品有名稱單價數量()
{
$item = $this->createItem('商品01', 100, 1);
$cart = new Cart();
$cart->put($item);
$this->assertArraySubset([$item], $cart->items());
}
/** @test */
public function 加總()
{
$cart = new Cart();
$cart->put($this->createItem('商品01', 100, 2));
$cart->put($this->createItem('商品02', 200, 1));
$this->assertEquals(400, $cart->total());
}
/** @test */
public function 移除商品()
{
$cart = new Cart();
$cart->put($item1 = $this->createItem('商品01', 100, 2));
$cart->put($item2 = $this->createItem('商品02', 200, 1));
$cart->remove($item1);
$this->assertEquals([$item2], $cart->items());
}
private function createItem($name, $price, $qty)
{
return new Item([
'name' => $name,
'price' => $price,
'quantity' => $qty,
]);
}
}
<?php
namespace Recca0120\Cart;
class Cart
{
private $items = [];
public function put($item)
{
array_push($this->items, $item);
return $this;
}
public function remove($item)
{
$this->items = array_values(array_filter($this->items, function($o) use ($item) {
return $o !== $item;
}));
}
public function items()
{
return $this->items;
}
public function total()
{
return array_sum(array_map(function ($item) {
return $item['total'];
}, $this->items));
}
}